package com.csdj.t309.geamtest.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.TreeMap;

import static com.csdj.t309.geamtest.service.Hashs.byteToString;


public class HttpRestUtil {

    private static Logger log = LoggerFactory.getLogger("httputil");

    public static <T> T requestForForm(String url, HttpMethod method, MultiValueMap<String, String> data, Class<T> clazz){
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type","application/x-www-form-urlencoded");
        headers.add("Accept","application/json");
        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(data,headers);
        try{
            ResponseEntity<T> resp = restTemplate.exchange(url, method,httpEntity,clazz);
            if(resp.getStatusCode() == HttpStatus.OK){
                return resp.getBody();
            }else{
                return null;
            }
        }catch (HttpClientErrorException e){
            log.error("http error uri:{}  response code:{}",url,e.getStatusCode());
            return null;
        }

    }

    public static <T> T requestForJson(String url, HttpMethod method, Object data, Class<T> clazz){
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type","application/json");
        headers.add("Accept","application/json");
        HttpEntity<Object> httpEntity = new HttpEntity<>(data,headers);
        ResponseEntity<T> resp = restTemplate.exchange(url, method,httpEntity,clazz);
        if(resp.getStatusCode() == HttpStatus.OK){
            return resp.getBody();
        }
        log.error("http error uri:{}  response code:{}",url,resp.getStatusCode());
        return null;
    }

    public static <T> T post(String url, MultiValueMap<String, String> data, Class<T> clazz){
        return requestForForm(url, HttpMethod.POST,data,clazz);
    }

    public static <T> T get(String url,Class<T> clazz){
        return requestForForm(url, HttpMethod.GET,null,clazz);
    }



}